package org.jeecg.module.flow.meter.tcpserver.tcpServer.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.module.flow.meter.tcpserver.dto.Cat1MessageDto;

import java.util.List;

import static org.jeecg.module.flow.meter.tcpserver.utils.FlowMeterUtils.*;

/**
 * @Author: 86176
 * @Date: 2024-05-22 8:31
 * @Version: 1.0
 */
@Slf4j
public class Cat1MessageDecoderHandler extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 13) {
            return;
        }
        // 读取报文头
        byte header = in.readByte();
        if (header != 0x68) {
            return;
        }

        // 表类型 16进制的41 4gcat流量计
        byte meterType = in.readByte();
        // 读取7字节编码表地址
        byte[] meterNumber = new byte[7];
        in.readBytes(meterNumber);

        //控制码
        byte controlCode = in.readByte();

        // 数据长度
        byte bodyLength = in.readByte();
        int bodyLengthInt = bodyLength & 0xFF;

        // 读取数据体
        byte[] body = new byte[bodyLengthInt];
        in.readBytes(body);

        Cat1MessageDto message = new Cat1MessageDto();

        // 读取和校验
        byte checksum = in.readByte();

        // 读取消息结束符
        byte endMarker = in.readByte();

        // 创建自定义的Cat1Message对象，并包含所有必要信息，然后添加到输出列表

        message.setHeader(byteToUnsignedHexString(header));
        message.setMeterType(Integer.parseInt(byteToUnsignedHexString(meterType)));
        message.setMeterNumber(toHexStringNoSpaces(meterNumber));
        message.setControlCode(Integer.parseInt(byteToUnsignedHexString(controlCode)));
        message.setBodyLength(bodyLength);
        message.setBody(toHexStringNoSpaces(body));
        message.setChecksum(byteToUnsignedHexString(checksum));
        message.setEndMarker(byteToUnsignedHexString(endMarker));
        out.add(message);
    }
}


